<template>
  <a-card :bordered="false" class="card-area" height="100%" bottom="auto">
    <a-form :form="form" :mcb00="mcb00">
      <h2>请填写运费模板信息</h2>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item label='模板名称' v-bind="formItemLayout">
            <a-input v-decorator="['mcb01', {rules: [
        { required: true, message: '模板名称不能为空'},
        {pattern:'^[\u4e00-\u9fa5\\\\w]+$',message:'请输入中文'}
        ]}]"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label='计费类型' v-bind="formItemLayout">
            <a-select style="width: 100%" :disabled="disabled" placeholder="请选择计费类型" v-decorator="['mcb02',{rules: [{ required: true, message: '请选择计费类型' }]}]" @change="handleChange">
              <a-select-option v-for="(item, index) in billingData" :key="index" :value="item">{{item}}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
          <a-col :span="8">
            <a-form-item label='目的地' v-bind="formItemLayout">
              <a-input v-decorator="['mcb09', {rules: [{ required: true, message: '目的地不能为空'}]}]" />
            </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24" v-if="mcb02 === 0">
        <a-col :span="8">
          <a-form-item label='首重KG' v-bind="formItemLayout">
            <a-input-number :min="1"  type="number" v-decorator="['mcb03', {rules: [{ required: true, message: '首重不能为空'}]}]" style="width: 100%"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label='首重费(元)' v-bind="formItemLayout">
            <a-input-number :min="1" type="number" v-decorator="['mcb04', {rules: [{ required: true, message: '首重费不能为空'}]}]" style="width: 100%"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label='次重费(元)' v-bind="formItemLayout">
            <a-input-number :min="1" type="number" v-decorator="['mcb05', {rules: [{ required: true, message: '次重费不能为空'}]}]" style="width: 100%"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24" v-if="mcb02 === 1">
        <a-col :span="8">
          <a-form-item label='首体积L' v-bind="formItemLayout">
            <a-input-number :min="1" type="number" v-decorator="['mcb06', {rules: [{ required: true, message: '首体积不能为空'}]}]" style="width: 100%"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label='首体费(元)' v-bind="formItemLayout">
            <a-input-number :min="1" type="number" v-decorator="['mcb07', {rules: [{ required: true, message: '首体费不能为空'}]}]" style="width: 100%"/>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item label='次体费(元)' v-bind="formItemLayout">
            <a-input-number :min="1" type="number" v-decorator="['mcb08', {rules: [{ required: true, message: '次体费不能为空'}]}]" style="width: 100%"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item label='快递名称' v-bind="formItemLayout">
            <a-select style="width: 100%" placeholder="请选择" v-decorator="['mcb10', {rules: [{ required: true, message: '请选择快递名称' }]}]">
              <a-select-option v-for="item in trans" :key="item.mca00" :value="item.mca00">{{item.mca01}}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <h2>请选择发货信息</h2>
    <!--    发货信息表格-->
    <a-table  ref="TableInfo"
             :columns="columns"
             :dataSource="dataSource"
             :pagination="pagination"
             :loading="loading"
             :scroll="{ x: 900 }"
             :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
             :mcb11 = 'mcb11'
             @change="handleTableChange">
    </a-table>
    <div class="bootom-button" style="float:right;">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-card>
</template>
<script>

const formItemLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 18}
}
export default {
  components: {},
  name: 'McbAdd',
  data () {
    return {
      billingData: {
        billing1: '按重量',
        billing2: '按体积'
      },
      disabled: false,
      mcb00: '',
      mcb02: '0',
      mcb11: '',
      dataSource: [],
      selectedRowKeys: [],
      sortedInfo: null,
      paginationInfo: null,
      pagination: {
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      trans: [],
      loading: false,
      formItemLayout
    }
  },
  beforeCreate () {
    this.form = this.$form.createForm(this, {
      onFieldsChange: (props, fields) => {
        console.log(props)
        if (['mcb03', 'mcb04', 'mcb05'].some(e => {
          console.log(e)
          return props.getFieldValue(e)
        })) {
          this.disabled = true
        } else if (['mcb06', 'mcb07', 'mcb08'].some(e => {
          console.log(e)
          return props.getFieldValue(e)
        })) {
          this.disabled = true
        } else {
          this.disabled = false
        }
      }
    })
  },
  mounted () {
    this.fetch()
  },
  computed: {
    columns () {
      let {sortedInfo} = this
      sortedInfo = sortedInfo || {}
      return [{
        title: '公司名称',
        dataIndex: 'company'
      }, {
        title: '发件人',
        dataIndex: 'sendName'
      }, {
        title: '手机号',
        dataIndex: 'mobile'
      }, {
        title: '省份',
        dataIndex: 'provinceName'
      }, {
        title: '城市',
        dataIndex: 'cityName'
      }, {
        title: '区/县',
        dataIndex: 'expAreaName'
      }, {
        title: '详细地址',
        dataIndex: 'address'
      }, {
        title: '邮政编码',
        dataIndex: 'postCode'
      }]
    }
  },
  methods: {
    handleChange (value) {
      console.log(value)
      if (value === '按重量') {
        value = 0
        this.mcb02 = value
        console.log(this.mcb02)
      } else if (value === '按体积') {
        value = 1
        this.mcb02 = value
        console.log(this.mcb02)
      }
    },
    onSelectChange (selectedRowKeys) {
      console.log(selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
      for (let key in this.selectedRowKeys) {
        this.mcb11 = this.dataSource[selectedRowKeys[key]].id // 获取收货信息ID
        console.log(this.dataSource[this.selectedRowKeys[key]].id)
      }
    },
    handleTableChange (pagination, filters, sorter) {
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      this.paginationInfo = pagination
      this.filteredInfo = filters
      this.sortedInfo = sorter
      this.fetch({
        results: pagination.pageSize,
        page: pagination.current,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    reset () {
      // this.mcb11 = ''
      this.loading = false
      this.disabled = false
      this.selectedRowKeys = []
      // 重置分页
      this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
      if (this.paginationInfo) {
        this.paginationInfo.current = this.pagination.defaultCurrent
        this.paginationInfo.pageSize = this.pagination.defaultPageSize
      }
      // 重置列排序规则
      this.sortedInfo = null
      this.filteredInfo = null
      // 重置查询参数
      this.queryParams = {}
      // // 清空时间选择
      // this.$refs.createTime.reset()
      this.fetch()
      this.form.resetFields()
    },
    onClose () {
      this.reset()
    },
    handleSubmit () {
      if (this.dataSource.length < 1) {
        this.$message.warning('先去添加发货信息再试吧!')
        return
      }
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请至少选择一个发货信息!')
        return
      }
      if (this.selectedRowKeys.length > 1) {
        this.$message.warning('请最多选择一个发货信息!')
        return
      }
      this.form.validateFields((err, values) => {
        values.mcb00 = this.mcb00
        values.mcb11 = this.mcb11
        if (this.mcb02 === '按重量') {
          this.mcb02 = 0
        } else if (this.mcb02 === '按体积') {
          this.mcb02 = 1
        }
        values.mcb02 = this.mcb02
        if (!err) {
          this.loading = true
          console.log(values)
          this.$api.freight.postMcb(values).then((r) => {
            console.log(r)
            console.log(values)
            this.$emit('success')
            this.$message.success('新增运费模板成功')
            this.reset()
            this.$router.push({path: `mcb`})
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    fetch (params = {}) {
      this.loading = true
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
        params.pageSize = this.paginationInfo.pageSize
        console.log(params.pageSize)
        // 下一页
        params.pageNum = this.paginationInfo.current
        console.log(params.pageNum)
      } else {
        // 如果分页信息为空，则设置为默认值
        params.pageSize = this.pagination.defaultPageSize
        params.pageNum = this.pagination.defaultCurrent
      }
      this.$api.freight.getMcaList().then((r) => { // 获取快递信息
        console.log(r)
        let express = r.data.data
        this.trans = express
        console.log(this.trans)
      })
      this.loading = true
      this.$api.freight.getOrderSenderInfoList({...params}).then((r) => {
        console.log(r)
        let data = r.data.data
        this.loading = false
        if (data === null) {
          this.dataSource = []
        } else {
          this.dataSource = data.records
          const pagination = { ...this.pagination }
          console.log(pagination)
          pagination.total = data.total
          this.pagination = pagination
        }
      })
    }
  }
}
</script>
